package com.zhouzi.zhaoyang.ui.activity

import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.google.zxing.integration.android.IntentIntegrator
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.BalancePaymentBean
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.mvp.p.PaymentMethodsActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.IPayMethodsActivityView
import com.zhouzi.zhaoyang.service.PrintService
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import com.zhouzi.zhaoyang.util.MyHttp
import kotlinx.android.synthetic.main.pay_methods_activity.*

class PaymentMethodsActivity : BaseActivity(), IPayMethodsActivityView {
    override fun errorToken() {
        exitToLogin()
    }
    var p = PaymentMethodsActivityPresenter()

    init {
        p.attachView(this)
    }

    override fun payOrderSuccess(outTradeNo: String?) {

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易成功")
        startService(intent)

        p.getOrder(outTradeNo)

    }

    override fun payOrderFailed(msg: String) {

        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", msg)
        startService(intent)

    }


    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {
        orderDetail?.let {
            printProductInformation(orderDetail)
            MyHttp.report(orderDetail)

            val activity = Intent(mContext, MainActivity::class.java)
            startActivity(activity)

            finish()

        }

    }

    public fun printProductInformation(orderDetail: OrderDetailBean) {
        App.instance().initPrinter()
        val devices = getUsbDeviceList()
        if (devices.size == 0) {
            return
        }
        val deviceNames = devices.map {
            it.deviceName
        }
        MaterialDialog.Builder(App.mContext)
            .items(deviceNames)
            .itemsCallback { dialog, itemView, position, text ->
                val intent = Intent(App.mContext, PrintService::class.java)
                intent.putExtra("status", PrintService.CONNECT_DEVICE)
                intent.putExtra("usbDevice", devices[position])

                // 实体类
                App().putEntity(intent, orderDetail)

                startService(intent)
            }.show()


        App.instance().printOrder(orderDetail)

        startService(Intent(App.mContext, PrintService::class.java))

    }

    public fun getUsbDeviceList(): MutableList<UsbDevice> {
        val usbDevices = mutableListOf<UsbDevice>()
        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        val devices = usbManager.deviceList
        val deviceIterator = devices.values.iterator()
        if (devices.size > 0) {
            while (deviceIterator.hasNext()) {
                val usbDevice = deviceIterator.next()
                if (checkUsbDevicePidVid(usbDevice))
                    usbDevices.add(usbDevice)
            }
        }
        return usbDevices
    }

    private fun checkUsbDevicePidVid(dev: UsbDevice): Boolean {
        val pid = dev.productId
        val vid = dev.vendorId
        return (vid == 34918 && pid == 256 || vid == 1137 && pid == 85
                || vid == 6790 && pid == 30084
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 512
                || vid == 26728 && pid == 256 || vid == 26728 && pid == 768
                || vid == 26728 && pid == 1024 || vid == 26728 && pid == 1280
                || vid == 26728 && pid == 1536)
    }

    override fun getOrderFailed(msg: String?) {
    }


    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()
    }


    override fun getLayoutId(): Int {
        return R.layout.pay_methods_activity
    }


    private val balancePaymentBean: BalancePaymentBean?
        get() {
            var data = intent.getParcelableExtra<BalancePaymentBean>("data")
            return data
        }


    var money = 0L
    var yuan = ""
    override fun initView() {


        if (intent.getStringExtra("money") != null) {

            yuan = intent.getStringExtra("money")
            money = Calculator.yuan2Fen(yuan)
            tvApShowMoney.text = "原价" + yuan

        }

        var data = intent.getParcelableExtra<BalancePaymentBean>("data")

        if (data != null) {

            var totalFee = Calculator.fen2Yuan(data.totalFee!!.toLong())
            var memberFee = Calculator.fen2Yuan(data.memberFee!!.toLong())
            tvApShowVipMoney.visibility = View.VISIBLE
            tvApShowMoney.text = "原价：" + totalFee
            tvApShowVipMoney.text = "会员价：" + memberFee
        }

        viewClick()
    }

    private fun viewClick() {
        tvApBtn.setOnClickListener {
            finish()
        }

        tvScanCode.setOnClickListener {

            var intent = Intent(this, MorePaymentMethodsActivity::class.java)
            intent.putExtra("money", yuan)
            if (balancePaymentBean != null) {
                intent.putExtra("data", balancePaymentBean)

            }
            startActivity(intent)

        }


        tvBarCode.setOnClickListener {

            wxScan()
//            scan(this)


        }

    }

    private fun wxScan() {


        val wxScanHint = Intent(App.mContext, VoiceService::class.java)
        wxScanHint.putExtra("voiceStr", "请对准上方摄像头扫码")
        startService(wxScanHint)

        WxPayFace.getInstance().startCodeScanner( object  : IWxPayfaceCallback(){


            override fun response(info: MutableMap<Any?, Any?>?) {


                Log.e("startCodeScanner",info.toString())

                if (info != null){
                    var return_code = info.get("return_code")
                    var return_msg = info.get("return_msg")
                    var code_msg = info.get("code_msg")
                    var  resultString = "startCodeScanner, return_code : " + return_code + " return_msg : " + return_msg + " code_msg: " + code_msg
                    /**
                    这里添加业务自定义的工作即可 注意该回调在异步线程
                     **/
                    if (!TextUtils.isEmpty(code_msg.toString())){
                        val scanSucess = Intent(mContext, VoiceService::class.java)
                        scanSucess.putExtra("voiceStr", "扫码成功")
                        startService(scanSucess)
                        goodsNo = code_msg.toString()
                        payOrder()
                    }else{
                        val scanFaild = Intent(mContext, VoiceService::class.java)
                        scanFaild.putExtra("voiceStr", "扫码失败")
                        startService(scanFaild)
                    }
                }

            }
        })


    }


    public fun scan(activity: BaseActivity) {

        val intent = Intent(App.mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "请对准条码")
        startService(intent)


        IntentIntegrator(activity)
            .setCaptureActivity(MyScanActivity().javaClass)
            .setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
            .setPrompt("请对准二维码")// 设置提示语
            .setCameraId(0)// 选择摄像头,可使用前置或者后置
            .setBeepEnabled(false)// 是否开启声音,扫完码之后会"哔"的一声
            .setBarcodeImageEnabled(true)// 扫完码之后生成二维码的图片
            .initiateScan()// 初始化扫码

    }

    var goodsNo = "0"
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        var result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)


        if (result != null) {

            if (result.getContents() == null) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "扫码失败")
                startService(intent)
            } else {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "扫码成功")
                startService(intent)
                goodsNo = result.contents
                payOrder()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }

    }

    var deviceNO = Build.SERIAL
    private fun payOrder() {

        var data = intent.getParcelableExtra<BalancePaymentBean>("data")


        var map = mutableMapOf(
            Pair("faceCode", goodsNo),
            Pair("deviceNo", deviceNO),
            Pair("totalFee", money.toString())
        )
        if (data != null) {
            map.put("memberFee", data.memberFee.toString())
            map.put("phone", data.phone)

        }
        p.payOrder(map)
    }

    override fun onDestroy() {
        super.onDestroy()
        p.detachView()
    }


}
